package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.GENDER;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.IMTOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USERID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.USER_NAME;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.RandomnameBean;
import com.luoxiang.socialandroid.bean.RegisterBean;
import com.luoxiang.socialandroid.bean.RegistfailBean;
import com.luoxiang.socialandroid.bean.TokenBean;
import com.luoxiang.socialandroid.dialog.TipDialog;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.GlideEngine;
import com.luoxiang.socialandroid.utils.LoginUtil;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.lxj.xpopup.XPopup;
import com.netease.nis.quicklogin.QuickLogin;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropImageEngine;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import cn.net.shoot.sharetracesdk.AppData;
import cn.net.shoot.sharetracesdk.ShareTrace;
import cn.net.shoot.sharetracesdk.ShareTraceInstallListener;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

public class RegisterActivity extends BaseActivity {
    private ImageView icon_back, imgGetnameradom;
    private EditText et_name;
    private Button btn_goup;
    private String edittexts;
    private String birthday;
    private TextView tvbirthday;
    private String birthdayDate = "";
    private String randomname;
    private ImageView img_headset, img_nansheng, img_nvsheng;
    private RadioButton man, girl;
    private String gender;
    private Integer showcode;
    private String paths;
    private TextView tv_chushengriqi;
    /**
     * 用于上传的头像文件
     */
    File file;
    File PHOTO_DIR = null;// 拍照的照片存储位置
    String mFileName = "temp_cropped.jpg";// 图片名称
    String photoPath = "";// 图片保存路径
    public static final int PHOTO_ALBUM = 0x10;// 相册返回结果
    public static final int PHOTO_CAMERA = 0x11;// 拍照返回结果
    public static final int PHOTO_RESULT = 0x12;// 剪切返回结果
    private String inviteCode;
    private String channelCode;


    @Override
    protected void initListener() {
        ShareTrace.getInstallTrace(new ShareTraceInstallListener() {
            @Override
            public void onInstall(AppData data) {
                if (data.paramsData == null || data.paramsData.isEmpty()) {
                    return;
                }
                String[] inviteCode = data.paramsData.split("inviteCode=");
                String[] channelCode = data.paramsData.split("channelCode=");
                if (inviteCode.length == 2) {
                    RegisterActivity.this.inviteCode = inviteCode[1];
                }
                if (channelCode.length == 2) {
                    RegisterActivity.this.channelCode = channelCode[1];
                }
            }

            @Override
            public void onError(int code, String msg) {
                Toast.makeText(RegisterActivity.this, code + " " + msg, Toast.LENGTH_SHORT).show();
            }
        });
        icon_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showdialog();

            }
        });
        btn_goup.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                edittexts = et_name.getText().toString();
                String phone = MmkvUtil.INSTANCE.decodeString("phone");
                getgender();
                getRequest();
                getnameCheck(EXTRA, edittexts);
                if (paths != null) {
                    if (gender != null) {
                        if (birthdayDate == null || birthdayDate.isEmpty()) {
                            ToastUtils.showShort(R.string.mi_qingxuanzeshengri);
                            return;
                        }
                        getRegist(EXTRA, paths, phone, edittexts, gender, birthdayDate);
                    } else {
                        ToastUtils.showShort(R.string.mi_qingxuanzexingbie);
                    }
                } else {
                    if (birthdayDate == null || birthdayDate.isEmpty()) {
                        ToastUtils.showShort(R.string.mi_qingxuanzexingbie);
                        return;
                    }
                    getRegist(EXTRA, "", phone, edittexts, gender, birthdayDate);
                }
            }

            @Override
            protected void onFastClick() {

            }
        });

        tvbirthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimePicker();
            }
        });
        imgGetnameradom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getRequest();
                showLoading();
                getrandomName(EXTRA);
            }
        });
        img_headset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureSelector.create(RegisterActivity.this)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setCropEngine((fragment, srcUri, destinationUri, dataSource, requestCode) -> {
                            // 注意* 如果你实现自己的裁剪库，需要在Activity的.setResult();
                            // Intent中需要给MediaStore.EXTRA_OUTPUT，塞入裁剪后的路径；如果有额外数据也可以通过CustomIntentKey.EXTRA_CUSTOM_EXTRA_DATA字段存入；
                            UCrop uCrop = UCrop.of(srcUri, destinationUri, dataSource);
                            uCrop.setImageEngine(new UCropImageEngine() {
                                @Override
                                public void loadImage(Context context, String url, ImageView imageView) {
                                    Glide.with(context).load(url).into(imageView);
                                }

                                @Override
                                public void loadImage(Context context, Uri url, int maxWidth, int maxHeight, OnCallbackListener<Bitmap> call) {
                                    Glide.with(context).asBitmap().override(maxWidth, maxHeight).load(url).into(new CustomTarget<Bitmap>() {
                                        @Override
                                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                            if (call != null) {
                                                call.onCall(resource);
                                            }
                                        }

                                        @Override
                                        public void onLoadFailed(@Nullable Drawable errorDrawable) {
                                            if (call != null) {
                                                call.onCall(null);
                                            }
                                        }

                                        @Override
                                        public void onLoadCleared(@Nullable Drawable placeholder) {
                                        }
                                    });
                                }
                            });
                            uCrop.withAspectRatio(1, 1);
                            uCrop.start(fragment.requireActivity(), fragment, requestCode);
                        })
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                if (result.isEmpty()) {
                                    return;
                                }
                                Glide.with(RegisterActivity.this)
                                        .load(result.get(0).getCutPath())
                                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))//设置圆形头像
                                        .into(img_headset);
                                if (result.get(0).getCutPath() != null) {
                                    paths = getkey(result.get(0).getCutPath());
                                    getToken(result.get(0).getCutPath());

                                } else {
                                    ToastUtils.showShort(R.string.mi_qingshangchuantupianhouchongshi);
                                }
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            }
        });
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_register);
        setStatusBarTranslucent();
    }

    @Override
    protected void initView() {
        icon_back = findViewById(R.id.icon_back);
        et_name = findViewById(R.id.et_name);
        btn_goup = findViewById(R.id.btn_goup);
        tvbirthday = findViewById(R.id.tv_data);
        imgGetnameradom = findViewById(R.id.img_getnameradom);
        img_headset = findViewById(R.id.img_headset);
        man = findViewById(R.id.man);
        girl = findViewById(R.id.girl);
        img_nansheng = findViewById(R.id.img_nansheng);
        img_nvsheng = findViewById(R.id.img_nvsheng);
        tv_chushengriqi = findViewById(R.id.tv_chushengriqi);
        getrandomName(EXTRA);
        man.setChecked(true);
        if (man.isChecked()) {
            img_nansheng.setImageResource(R.mipmap.icon_nansheng);
            img_nvsheng.setImageResource(R.mipmap.icon_nvshengfalse);
            man.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            img_nvsheng.setImageResource(R.mipmap.icon_nvsheng);
            img_nansheng.setImageResource(R.mipmap.icon_nanshengfalse);
        }
        MmkvUtil.INSTANCE.encode(GENDER, 1);
        man.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    img_nansheng.setImageResource(R.mipmap.icon_nansheng);
                    img_nvsheng.setImageResource(R.mipmap.icon_nvshengfalse);
                    man.setTextColor(Color.parseColor("#FFFFFF"));
                    girl.setTextColor(Color.parseColor("#666666"));
                    MmkvUtil.INSTANCE.encode(GENDER, 1);
                } else {
                    img_nvsheng.setImageResource(R.mipmap.icon_nvsheng);
                    img_nansheng.setImageResource(R.mipmap.icon_nanshengfalse);
                    man.setTextColor(Color.parseColor("#666666"));
                    girl.setTextColor(Color.parseColor("#FFFFFF"));
                    MmkvUtil.INSTANCE.encode(GENDER, 0);
                }
            }
        });

//        if (man.isChecked()) {
//            img_nansheng.setImageResource(R.mipmap.icon_nansheng);
//            img_nvsheng.setImageResource(R.mipmap.icon_nvshengfalse);
//        } else if (girl.isChecked()) {
//            img_nvsheng.setImageResource(R.mipmap.icon_nvsheng);
//            img_nansheng.setImageResource(R.mipmap.icon_nanshengfalse);
//        }
    }

    private void showdialog() {
        TipDialog tipDialog = new TipDialog(RegisterActivity.this);
        tipDialog.setTitle(getString(R.string.mi_caozuotishi));
        tipDialog.setCancel(getString(R.string.mi_fangqizhuce));
        tipDialog.setContent(getString(R.string.mi_dialog_zhuce_content));
        tipDialog.setConfirm(getString(R.string.mi_queding));
        tipDialog.setOnCancelClickListener(new Function0<Unit>() {
            @Override
            public Unit invoke() {
                tipDialog.dismiss();
                return null;
            }
        });
        tipDialog.setOnConfirmClickListener(() -> {

            LoginUtil.Companion.initLogin(
                    RegisterActivity.this,
                    result -> {
                        LoginUtil.Companion.startLogin(RegisterActivity.this, result);
                        finish();
                        return null;
                    },
                    () -> {
                        showLoading();
                        return null;
                    },
                    () -> {
                        clearLoading();
                        return null;
                    });
            return null;
        });
        new XPopup.Builder(RegisterActivity.this)
                .asCustom(tipDialog)
                .show();
    }

    private void getgender() {
        if (man.isChecked()) {
            gender = "1";
        } else if (girl.isChecked()) {
            gender = "0";
        }
    }

    /**
     * 检查用户名重复的查重方法
     *
     * @param extra
     * @param name
     */
    private void getnameCheck(String extra, String name) {
        NetUtils.getInstance().getApiService().getnameCheck(extra, name)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(numberBean.getData(), KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();
                        RegistfailBean registfailBean = gson.fromJson(decryptStr, RegistfailBean.class);
                        if (registfailBean != null) {
                            showcode = registfailBean.getCode();

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    private void showTimePicker() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                //LogUtils.v(TimeUtil.dateToString(date));
                String format = simpleDateFormat.format(date.getTime());
                birthdayDate = format;
                tvbirthday.setText(format);
                tvbirthday.setTextColor(Color.parseColor("#333333"));
                tv_chushengriqi.setTextColor(Color.parseColor("#333333"));
            }
        }).build();
        String s = "2001-01-01";
        if (!StringUtils.isEmpty(s)) {
            try {
                Date parse = simpleDateFormat.parse(s);
                Calendar cal = Calendar.getInstance();
                cal.setTime(parse);
                pvTime.setDate(cal);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        pvTime.show();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            showdialog();
            return false;

        } else {

            return super.onKeyDown(keyCode, event);

        }
    }

    /**
     * 获取用户名的方法
     */
    private void getrandomName(String extra) {
        NetUtils.getInstance().getApiService().getrandomName(extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(numberBean.getData(), KEY);
                            Gson gson = new Gson();
                            RandomnameBean randomnameBean = gson.fromJson(decryptStr, RandomnameBean.class);
                            if (randomnameBean != null) {
                                if (randomnameBean.getData() != null) {
                                    randomname = randomnameBean.getData().getName();
                                    et_name.setText(randomname);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        clearLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getToken(String picturePaths) {
//        List<String> paths=new ArrayList<>();
        getRequest();
        NetUtils2.getInstance().getApiService().getUploadToken()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {


                            LogUtils.i("decryptStrpp", decryptStr);
                            Gson gson = new Gson();
                            TokenBean tokenBean = gson.fromJson(decryptStr, TokenBean.class);
                            if (tokenBean != null) {
                                String endpoint = tokenBean.getData().getSts().getEndpoint();

                                // 在移动端建议使用STS的方式初始化OSSClient。
                                OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(tokenBean.getData().getSts().getAccessKeyId(), tokenBean.getData().getSts().getAccessKeySecret(), tokenBean.getData().getSts().getSecurityToken());

                                ClientConfiguration conf = new ClientConfiguration();
                                conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒。
                                conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒。
                                conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个。
                                conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次。

                                OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
//                                for (String localPath:picturePaths) {

                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/HHmmss/");
                                Date date = new Date(System.currentTimeMillis());
                                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                //文件后缀   例如：.png
                                String fileType = picturePaths.substring(picturePaths.lastIndexOf("."));
//                                String path = "exampledir/exampleobject.txt";

                                LogUtils.i("pathiii", key);
                                // 构造上传请求。
//                                2022/09/29/191405/UUID.PNG
                                PutObjectRequest putObjectRequest = new PutObjectRequest(tokenBean.getData().getSts().getBucketName(), paths, picturePaths);

                                putObjectRequest.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                                    @Override
                                    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                                    }
                                });
                                OSSAsyncTask ossAsyncTask = oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                                    @Override
                                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//                                        paths.add(path);
                                        LogUtils.d("aliossresult", "上传成功" + "diyi\t\t" + result.toString() + "\t\tdier=" + request.toString());
                                    }

                                    @Override
                                    public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                        LogUtils.d("aliossresult", "上传失败");

                                    }
                                });
//                            }
                                LogUtils.i("ossmin", oss.toString());
                            }

                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 注册
     */
    private void getRegist(String extra, String icon, String thirdId, String name, String gender, String birth) {
        NetUtils.getInstance().getApiService().getRegist(extra, icon, thirdId, name, gender, birth, inviteCode, channelCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();
                        RegisterBean registerBeans = gson.fromJson(decryptStr, RegisterBean.class);
                        if (registerBeans != null) {
                            if (registerBeans.getData() != null) {
                                if (registerBeans.getData().getUser() != null) {
                                    if (showcode != null && showcode == 0) {
                                        if (registerBeans.getCode() == 0) {
                                            int userId = registerBeans.getData().getUser().getId();
                                            MmkvUtil.INSTANCE.encode(USERID, userId);
                                            String token = registerBeans.getData().getUser().getToken();
                                            LogUtils.d("token", token);
                                            //成功,可以注册
                                            MmkvUtil.INSTANCE.encode("isshowdialogbatch", "showdialog");
                                            MmkvUtil.INSTANCE.encode("keybutezhi", "");
                                            Intent intent = new Intent(RegisterActivity.this, Tezhi1Activity.class);
                                            MmkvUtil.INSTANCE.encode(TOKEN, token);
                                            MmkvUtil.INSTANCE.encode(ACCID, registerBeans.getData().getUser().getId());
                                            MmkvUtil.INSTANCE.encode(IMTOKEN, registerBeans.getData().getUser().getImToken());
                                            MmkvUtil.INSTANCE.encode("sexpait", gender);
                                            intent.putExtra("token", registerBeans.getData().getUser().getToken());

                                            startActivity(intent);

                                            ToastUtils.showShort(R.string.mi_zhucechenggong);
                                            MmkvUtil.INSTANCE.encode(USER_NAME, registerBeans.getData().getUser().getName());

                                            finish();
                                        } else {
                                            ToastUtils.showShort(registerBeans.getMsg());
                                        }
                                    } else {
                                        ToastUtils.showShort(R.string.mi_yonghumingyibeizhuce);
                                    }
                                }
                            }
                            if (registerBeans.getCode() != 0) {
                                ToastUtils.showShort(registerBeans.getMsg());
                            }

                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}